package com.atguigu.deployment;

import com.atguigu.pojo.WordCount;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**

 * flimk两种运行模式测试：会话模式和应用模式
 *
 * 步骤:
 *   0.向main方法中传参
 *
 *   1. 创建执行环境
 *
 *   2. 从数据源读取数据
 *
 *   3. 对读取到的数据进行转换处理
 *
 *   4. 写出结果
 *
 *   5. 启动执行
 *
 */
public class wordCount {
    public static void main(String[] args) {

        System.out.println("main.............");

        //通过参数名来获取地址

        ParameterTool parameterTool = ParameterTool.fromArgs(args);
        String hostname = parameterTool.get("hostname");//这里必须使用hostname
        int port = parameterTool.getInt("port");


        //对接移动网页
        /*Configuration conf = new Configuration();
        conf.setString("rest.address","localhost");
        conf.setInteger("rest.port",5678);*/



        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //将对接数据源的参数传过来
        DataStreamSource<String> ds = env.socketTextStream(hostname , port);

        SingleOutputStreamOperator<WordCount> flatMapds = ds.flatMap(
                new FlatMapFunction<String, WordCount>() {
                    @Override
                    public void flatMap(String line, Collector<WordCount> out) throws Exception {

                        String[] words = line.split(" ");
                        for (String word : words) {

                            out.collect(new WordCount(word,1L));
                        }
                    }
                }
        );

        KeyedStream<WordCount,String> keyBy = flatMapds.keyBy(
                new KeySelector<WordCount,String>() {
                    @Override
                    public String getKey(WordCount wordCount) throws Exception {
                        return wordCount.getWord();
                    }
                }
        );
        SingleOutputStreamOperator<WordCount> sumds = keyBy.sum("count");

        sumds.print();

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
